package xyz.missou.blog.controller.manage;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import xyz.missou.blog.controller.BaseController;
import xyz.missou.blog.entity.User;
import xyz.missou.blog.service.UserService;

import javax.annotation.Resource;

@Controller
@RequestMapping("/manage/user")
public class ManageUserController extends BaseController {

    @Resource
    private UserService userService;

    @RequestMapping({"/add/","/add"})
    public String add(RedirectAttributes redirectAttributes, @RequestParam("account") String account, @RequestParam("nickname") String nickname, @RequestParam("password") String password){
        User user=userService.getUserByAccount(account);
        if (user==null){
            user=new User();
            user.setAccount(account);
            user.setNickname(nickname);
            user.setPassword(password);
            userService.addUser(user);
        }else {
            redirectAttributes.addAttribute("msg","该账号已存在，请更换账号后重新添加！");
        }
        return "redirect:/manage/user/";
    }

    @RequestMapping({"/update/{id}/","/update/{id}"})
    public String update(RedirectAttributes redirectAttributes,@PathVariable("id") Integer id, @RequestParam("account") String account, @RequestParam("nickname") String nickname){
        User user=userService.getUserByAccount(account);
        if (user==null || user.getId()==id){
            user=new User();
            user.setId(id);
            user.setAccount(account);
            user.setNickname(nickname);
            userService.updateUser(user);
        }else {
            redirectAttributes.addAttribute("msg","该账号已存在，请更换账号后重新修改！");
        }
        return "redirect:/manage/user/";
    }

    @RequestMapping({"/delete/{id}/","/delete/{id}"})
    public String delete(@PathVariable("id") Integer id){
        userService.deleteUserById(id);
        return "redirect:/manage/user/";
    }
}
